package com.mapper;

import com.pojo.ChatMessage;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ChatMapper {

    /**
     * 保存聊天消息
     */
    @Insert("INSERT INTO chat_messages (sender_id, receiver_id, content, created_at, is_read) " +
            "VALUES (#{senderId}, #{receiverId}, #{content}, #{createdAt}, #{isRead})")
    @Options(useGeneratedKeys = true, keyProperty = "id") // 获取自增主键值
    void insertMessage(ChatMessage message);

    /**
     * 标记消息为已读
     * 只允许接收者标记自己的消息
     */
    @Update("UPDATE chat_messages SET is_read = #{read} " +
            "WHERE id = #{id} AND receiver_id = #{userId}")
    void updateReadStatus(
            @Param("id") Integer messageId,
            @Param("userId") Integer userId,
            @Param("read") boolean read
    );

    /**
     * 获取两个用户之间的聊天历史（分页）
     */
    @Select("SELECT id, sender_id AS senderId, receiver_id AS receiverId, content, created_at AS createdAt, is_read AS isRead " +
            "FROM chat_messages " +
            "WHERE (sender_id = #{userId1} AND receiver_id = #{userId2}) " +
            "   OR (sender_id = #{userId2} AND receiver_id = #{userId1}) " +
            "ORDER BY created_at DESC " +
            "LIMIT #{offset}, #{size}")
    List<ChatMessage> getMessagesBetweenUsers(
            @Param("userId1") Integer userId1,
            @Param("userId2") Integer userId2,
            @Param("offset") int offset,
            @Param("size") int size
    );

    /**
     * 统计用户的未读消息数
     */
    @Select("SELECT COUNT(*) " +
            "FROM chat_messages " +
            "WHERE receiver_id = #{userId} AND is_read = FALSE")
    int countUnreadByUserId(@Param("userId") Integer userId);
}